package com.msb.proxy.v06;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

/**
 * 分离代理行为与被代理对象
 * 使用 JDK动态代理
 */
public class Tank implements Movable {
    @Override
    public void move() {
        System.out.println("tank moving ... ~");
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Tank tank = new Tank();

        // 将中间生成的类保存到本地
        System.getProperties().put("jdk.proxy.ProxyGenerator.saveGeneratedFiles", "true");

        Movable m = (Movable) Proxy.newProxyInstance(Tank.class.getClassLoader(),
                new Class[]{Movable.class}, new TimeProxy(tank));

        m.move();
    }
}

class TimeProxy implements InvocationHandler {

    Movable move;

    public TimeProxy(Movable move) {
        this.move = move;
    }

    public void before() {
        System.out.println("method starting ... ~");
    }

    public void after() {
        System.out.println("method stopping ... ~");
    }

    @Override
    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
        before();
        Object invoke = method.invoke(move, objects);
        after();
        return invoke;
    }
}

interface Movable {
    void move();
}